package com.itheima.putige.putige.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.putige.putige.common.CustomException;
import com.itheima.putige.putige.common.R;
import com.itheima.putige.putige.dto.DishDto;
import com.itheima.putige.putige.dto.SetmealDto;
import com.itheima.putige.putige.entity.Category;
import com.itheima.putige.putige.entity.Dish;
import com.itheima.putige.putige.entity.Setmeal;
import com.itheima.putige.putige.entity.SetmealDish;
import com.itheima.putige.putige.service.CategoryService;
import com.itheima.putige.putige.service.DishService;
import com.itheima.putige.putige.service.SetmealDishService;
import com.itheima.putige.putige.service.SetmealService;
import com.itheima.putige.putige.utils.QiniuCloudUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Value("${reggie.path}")
    private String basePath;

    @Autowired(required=false)
    private SetmealService setmealService;

    @Autowired(required=false)
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true) //清除setmealCache名称下,所有的缓存数据
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("套餐信息：{}",setmealDto);
        String image = setmealDto.getImage();
        try {
            if (image.contains("lstp")){
                log.info("将临时文件存入云端");
                image = QiniuCloudUtil.putFile(basePath+image);
                setmealDto.setImage(image);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }

    /**
     * 移动端查看套餐详情
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<DishDto>> dish(@PathVariable Long id) {
        log.info("id为：{}", id);
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null, SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(lqw);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            dishDto.setCopies(item.getCopies());
            Long dishId = item.getDishId();
            LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
            qw.eq(dishId != null, Dish::getId, dishId);
            Dish dish = dishService.getOne(qw);
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据name进行like模糊查询
        queryWrapper.like(name != null,Setmeal::getName,name);
        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item,setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                //分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)//清除setmealCache名称下，所有的缓存数据
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = setmealService.count(queryWrapper);
        if (count >0){
            throw new CustomException("套餐正在销售,无法删除");
        }
        for (Long id : ids) {
            String image = setmealService.getById(id).getImage();
            if (image.contains("qn.zcscloud.cn")){
                QiniuCloudUtil.delete(image.split("qn.zcscloud.cn/")[1]);
            }
        }

        setmealService.removeWithDish(ids);

        return R.success("套餐数据删除成功");
    }

    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        //条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 修改套餐状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> update(@PathVariable int status,@RequestParam List<Long> ids){
        log.info("修改订单状态，ids:{}",ids);
        UpdateWrapper<Setmeal> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().in(Setmeal::getId,ids);
        updateWrapper.lambda().set(Setmeal::getStatus,status);
        boolean update = setmealService.update(updateWrapper);
        return R.success("状态修改成功");
    }

    /**
     * 根据id查询套餐信息和对应的菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id){

        SetmealDto setmealDto = setmealService.getByIdDish(id);

        return R.success(setmealDto);
    }

    /**
     * 套餐修改成功
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        log.info(setmealDto.toString());
        String image = setmealDto.getImage();
        try {
            //判断之前的图片是否来自云端,是的话先移除
            if (image.contains("qn.zcscloud.cn")){
                QiniuCloudUtil.delete(image.split("qn.zcscloud.cn/")[1]);
            }
            //加载现在的图片
            String file = QiniuCloudUtil.putFile(basePath + image);
            setmealDto.setImage(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        setmealService.updateSetmeal(setmealDto);
        return R.success("修改套餐成功");
    }


}
